package com.pesilo.mvc.view.component.module.backgroundModule
{
	import com.greensock.TweenMax;
	import com.greensock.easing.Linear;
	import com.pesilo.event.PesiloEvent;
	
	import flash.display.Bitmap;
	import flash.display.Sprite;
	import flash.events.Event;

	public class BgItemComponent extends Sprite
	{
		public var bitmap:Bitmap
		private var endX:Number;
		private var endY:Number;
		private var endNum:Number;
		private var isfirst:Boolean=false;
		private var disX:Number;
		private var disY:Number;
		public function BgItemComponent(bitmap:Bitmap,isfirst:Boolean=false) 
		{
			this.isfirst=isfirst;
			this.bitmap = bitmap;
			this.addEventListener(Event.ADDED_TO_STAGE, __addtoStageHandle, false, 0, true);
		}
		
		private function __addtoStageHandle(e:Event):void 
		{
			removeEventListener(Event.ADDED_TO_STAGE, __addtoStageHandle);
			this.addEventListener(Event.REMOVED_FROM_STAGE, __removeFromStageHandle, false, 0, true);
			this.addChild(bitmap);
			
//			if (!ModelLocator.enableAnimation) return;
			if (this.bitmap.x < 0) endX = 0;
			else endX = stage.stageWidth - bitmap.width;
			
			if (this.bitmap.y < 0) endY = 0;
			else endY = stage.stageHeight - bitmap.height;
			if(!isfirst)
				this.bitmap.alpha = 0;
			disX=endX-this.bitmap.x;
			disY=endY-this.bitmap.y;
			
			endX=bitmap.x+disX/4;
			endY=bitmap.y+disY/4;
			TweenMax.to(bitmap,3,{ease:Linear.easeNone,x:endX,y:endY,alpha:1,onComplete:__onCompleteHandle1});
			
		}
		
		public function stop():void {
			TweenMax.killTweensOf(bitmap);
			this.dispatchEvent(new PesiloEvent(PesiloEvent.EVENT_BACKGROUD_MOVE_END));
			this.parent.removeChild(this);
		}
		
		private function __onCompleteHandle1():void {
			endX=bitmap.x+disX/2;
			endY=bitmap.y+disY/2;
			TweenMax.to(bitmap,7,{ease:Linear.easeNone,x:endX,y:endY,onComplete:__onCompleteHandle2});
		}
		
		private function __onCompleteHandle2():void {
			endX=bitmap.x+disX/4;
			endY=bitmap.y+disY/4;
			this.dispatchEvent(new PesiloEvent(PesiloEvent.EVENT_BACKGROUD_MOVE_END));
			TweenMax.to(bitmap,3,{ease:Linear.easeNone,x:endX,y:endY,alpha:0,onComplete:__onCompleteHandle3});
		}
		
		private function __onCompleteHandle3():void {
			this.parent.removeChild(this);
		}
				
		private function __removeFromStageHandle(e:Event):void 
		{
			removeEventListener(Event.REMOVED_FROM_STAGE, __removeFromStageHandle);
			dispose();
		}
		
		private function dispose():void{
			while (this.numChildren) this.removeChildAt(0);
			bitmap = null;
		}
		
	}

}